<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { Plus, Delete, User, Edit, Download } from "@element-plus/icons-vue";
import {
  getTeamByPage,
  getTeamMembersByPage,
  getTeamAccountsByPage,
  createTeam,
  getPageMemberByAccount,
  getPageAccountByMember,
  createTeamAccount,
  getMyTeamAccount,
  addTeamMember,
  getpageApplyJoin,
  approvalJoinTeam,
  addAccountMember,
  updateMemberRole,
  stopAccountMember,
  getPageApplyJoinTeamAccount,
  approvalJoinTeamAccount,
  startAccountMember
} from "@/api";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import QRCode from "qrcode.vue";

interface TeamInfo {
  id: number;
  uuid: string;
  name: string;
  status: string;
  remark: string | null;
  created_at: string;
  updated_at: string;
  description: string | null;
}

interface TeamResponse {
  records: TeamInfo[];
  pagination: {
    total: number;
    per_page: number;
    current_page: number;
    last_page: number;
    has_more: boolean;
    has_last: boolean;
  };
}

interface AccountInfo {
  id: number;
  team_id: number;
  account_number: string;
  status: string;
  remark: string | null;
  created_at: string;
  updated_at: string;
  name: string;
  description: string;
}

interface AccountResponse {
  records: AccountInfo[];
  pagination: {
    total: number;
    per_page: number;
    current_page: number;
    last_page: number;
    has_more: boolean;
    has_last: boolean;
  };
}

interface MemberInfo {
  id: number;
  team_id: number;
  henau_number: string;
  name: string;
  status: string;
  remark: string | null;
  created_at: string;
  updated_at: string;
  role: string;
}

interface MemberResponse {
  records: MemberInfo[];
  pagination: {
    total: number;
    per_page: number;
    current_page: number;
    last_page: number;
    has_more: boolean;
    has_last: boolean;
  };
}

interface AccountMemberInfo {
  id: number;
  team_id: number;
  member_id: number;
  account_id: number;
  status: string;
  remark: string | null;
  created_at: string;
  updated_at: string;
  member_name: string;
  henau_number: string;
  team_role: string;
}

interface AccountMemberResponse {
  records: AccountMemberInfo[];
  pagination: {
    total: number;
    per_page: number;
    current_page: number;
    last_page: number;
    has_more: boolean;
    has_last: boolean;
  };
}

interface AccountHistoryInfo {
  id: number;
  team_id: number;
  account_name: string;
  description: string;
  reviewer_id: number | null;
  status: string;
  remark: string | null;
  created_at: string;
  updated_at: string;
  initiator_id: number;
  team_name: string;
  reviewer_name: string | null;
}

interface AccountHistoryResponse {
  records: AccountHistoryInfo[];
  pagination: {
    total: number;
    per_page: number;
    current_page: number;
    last_page: number;
    has_more: boolean;
    has_last: boolean;
  };
}

interface CreateAccountForm {
  team_id: number;
  account_name: string;
  description: string;
}

interface AddMemberForm {
  team_id: number;
  henau_number: string;
  name: string;
  role: string;
}

interface ApplyJoinInfo {
  id: number;
  team_id: number;
  initiator_henau_number: string;
  initiator_name: string;
  reviewer_id: number;
  status: string;
  remark: string | null;
  created_at: string;
  updated_at: string;
  team_name: string;
  reviewer_name: string | null;
}

interface ApplyJoinResponse {
  records: ApplyJoinInfo[];
  pagination: {
    total: number;
    per_page: number;
    current_page: number;
    last_page: number;
    has_more: boolean;
    has_last: boolean;
  };
}

interface ApplyJoinAccountInfo {
  id: number;
  account_id: number;
  initiator_henau_number: string;
  initiator_name: string;
  reviewer_id: number;
  status: string;
  remark: string | null;
  created_at: string;
  updated_at: string;
}

interface ApplyJoinAccountResponse {
  records: ApplyJoinAccountInfo[];
  pagination: {
    total: number;
    per_page: number;
    current_page: number;
    last_page: number;
    has_more: boolean;
    has_last: boolean;
  };
}

const loading = ref(false);
const teamList = ref<TeamInfo[]>([]);
const teamTotal = ref(0);
const currentTeam = ref<TeamInfo | null>(null);

const accountList = ref<AccountInfo[]>([]);
const memberList = ref<MemberInfo[]>([]);

const accountTotal = ref(0);
const memberTotal = ref(0);

const accountQuery = ref({
  page: 1,
  size: 10,
  team_id: 1
});

const memberQuery = ref({
  page: 1,
  size: 10,
  team_id: 1
});

const teamQuery = ref({
  page: 1,
  size: 10
});

// 添加创建团队的表单数据和对话框控制
const createTeamDialogVisible = ref(false);
const createTeamForm = ref({
  team_name: "",
  description: ""
});
const createTeamFormRef = ref<FormInstance>();
const createTeamRules = {
  team_name: [
    { required: true, message: "请输入团队名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
  ],
  description: [
    { max: 200, message: "团队描述不能超过200个字符", trigger: "blur" }
  ]
};

const accountMemberDialogVisible = ref(false);
const currentAccountId = ref<number | null>(null);
const accountMembers = ref<AccountMemberInfo[]>([]);
const accountMemberTotal = ref(0);
const accountMemberQuery = ref({
  page: 1,
  size: 10,
  account_id: null as number | null
});

const memberAccountDialogVisible = ref(false);
const currentMemberId = ref<number | null>(null);
const memberAccounts = ref<AccountInfo[]>([]);
const memberAccountTotal = ref(0);
const memberAccountQuery = ref({
  page: 1,
  size: 10,
  team_id: null as number | null,
  member_id: null as number | null
});

const createAccountDialogVisible = ref(false);
const createAccountForm = ref<CreateAccountForm>({
  team_id: 1,
  account_name: "",
  description: ""
});
const createAccountFormRef = ref<FormInstance>();
const createAccountRules = {
  account_name: [
    { required: true, message: "请输入账号名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
  ],
  description: [{ max: 200, message: "描述不能超过200个字符", trigger: "blur" }]
};

const accountHistoryDialogVisible = ref(false);
const accountHistoryList = ref<AccountHistoryInfo[]>([]);
const accountHistoryTotal = ref(0);
const accountHistoryQuery = ref({
  page: 1,
  size: 10,
  team_id: null as number | null
});

const addMemberDialogVisible = ref(false);
const activeTab = ref("manual");
const addMemberForm = ref<AddMemberForm>({
  team_id: 1,
  henau_number: "",
  name: "",
  role: "member"
});
const addMemberFormRef = ref<FormInstance>();
const addMemberRules = {
  henau_number: [
    { required: true, message: "请输入学工号", trigger: "blur" },
    { min: 5, max: 20, message: "长度在 5 到 20 个字符", trigger: "blur" }
  ],
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  role: [{ required: true, message: "请选择角色", trigger: "change" }]
};

const applyJoinDialogVisible = ref(false);
const applyJoinList = ref<ApplyJoinInfo[]>([]);
const applyJoinTotal = ref(0);
const applyJoinQuery = ref({
  page: 1,
  size: 10,
  team_id: null as number | null
});

// 添加新的响应式变量
const addMemberToAccountDialogVisible = ref(false);
const teamMemberSearchQuery = ref("");
const teamMemberSearchList = ref<MemberInfo[]>([]);
const selectedTeamMemberId = ref<number | null>(null);
const teamMemberSearchLoading = ref(false);

// 添加计算属性获取选中的成员
const selectedTeamMember = computed(() =>
  teamMemberSearchList.value.find(
    member => member.id === selectedTeamMemberId.value
  )
);

// 添加修改角色相关的变量
const editRoleDialogVisible = ref(false);
const currentEditMember = ref<MemberInfo | null>(null);
const editRoleForm = ref({
  role: "",
  status: "approved"
});

const qrcodeRef = ref<HTMLElement | null>(null);

// 添加新的响应式变量
const addAccountToMemberDialogVisible = ref(false);
const selectedAccountId = ref<number | null>(null);
const availableAccounts = ref<AccountInfo[]>([]);
const availableAccountsTotal = ref(0);
const availableAccountsQuery = ref({
  page: 1,
  size: 10,
  team_id: null as number | null
});

const accountMemberActiveTab = ref("list");
const accountQrcodeRef = ref<HTMLElement | null>(null);

const applyJoinAccountDialogVisible = ref(false);
const applyJoinAccountList = ref<ApplyJoinAccountInfo[]>([]);
const applyJoinAccountTotal = ref(0);
const applyJoinAccountQuery = ref({
  page: 1,
  size: 10,
  team_id: null as number | null,
  account_id: null as number | null
});

const getTeams = async () => {
  try {
    loading.value = true;
    const res = await getTeamByPage(teamQuery.value);
    if (res.data) {
      teamList.value = res.data.records;
      teamTotal.value = res.data.pagination.total;
      // 设置当前选中的团队为第一个团队
      if (teamList.value.length > 0) {
        currentTeam.value = teamList.value[0];
        // 更新账号和成员查询的team_id
        accountQuery.value.team_id = currentTeam.value.id;
        memberQuery.value.team_id = currentTeam.value.id;
        // 重新获取账号和成员数据
        getAccounts();
        getMembers();
      }
    }
  } finally {
    loading.value = false;
  }
};

const getAccounts = async () => {
  try {
    loading.value = true;
    const res = await getTeamAccountsByPage(accountQuery.value);
    if (res.data) {
      accountList.value = res.data.records;
      accountTotal.value = res.data.pagination.total;
    }
  } finally {
    loading.value = false;
  }
};

const getMembers = async () => {
  try {
    loading.value = true;
    const res = await getTeamMembersByPage(memberQuery.value);
    if (res.data) {
      memberList.value = res.data.records;
      memberTotal.value = res.data.pagination.total;
    }
  } finally {
    loading.value = false;
  }
};

const handleTeamChange = (team: TeamInfo) => {
  currentTeam.value = team;
  accountQuery.value.team_id = team.id;
  memberQuery.value.team_id = team.id;
  getAccounts();
  getMembers();
};

const handleApplyTeam = () => {
  createTeamDialogVisible.value = true;
};

const submitCreateTeam = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate(async valid => {
    if (valid) {
      try {
        loading.value = true;
        await createTeam(createTeamForm.value);
        ElMessage.success("申请创建团队成功等待审批");
        createTeamDialogVisible.value = false;
        // 重置表单
        createTeamForm.value = {
          team_name: "",
          description: ""
        };
        // 刷新团队列表
        getTeams();
      } catch (error: any) {
        ElMessage.error(error.message || "创建团队失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

const cancelCreateTeam = () => {
  createTeamDialogVisible.value = false;
  createTeamForm.value = {
    team_name: "",
    description: ""
  };
};

const handleAddMember = () => {
  if (!currentTeam.value) {
    ElMessage.warning("请先选择团队");
    return;
  }
  addMemberForm.value.team_id = currentTeam.value.id;
  addMemberDialogVisible.value = true;
};

const handleRemoveMember = (row: MemberInfo) => {
  handleViewMemberAccounts(row.id);
};

const handleAddAccount = () => {
  if (!currentTeam.value) {
    ElMessage.warning("请先选择团队");
    return;
  }
  createAccountForm.value.team_id = currentTeam.value.id;
  createAccountDialogVisible.value = true;
};

const handleRemoveAccount = (row: AccountInfo) => {
  // TODO: 实现移除账号逻辑
  console.log("移除账号", row);
};

const getRoleTagType = (role: string) => {
  switch (role) {
    case "admin":
      return "danger";
    case "member":
      return "info";
    default:
      return "info";
  }
};

const getRoleText = (role: string) => {
  switch (role) {
    case "admin":
      return "管理员";
    case "member":
      return "组员";
    default:
      return "未知";
  }
};

const getOAuthUrl = computed(() => {
  if (!currentTeam.value) return "";
  // 构建完整的回调URL，确保参数使用&连接
  const redirectUri = encodeURIComponent(
    `${window.location.origin}/#/ApproveTeam?uuid=${currentTeam.value.uuid}&code=CODE_PLACEHOLDER`
  );
  return `https://oauth.henau.edu.cn/oauth2_connect/authorize?appid=ndd956a392c8b55d39&redirect_uri=${redirectUri}&response_type=code&scope=henauapi_userinfo`;
});

const handleViewAccountMembers = async (accountId: number) => {
  currentAccountId.value = accountId;
  accountMemberQuery.value.account_id = accountId;
  accountMemberDialogVisible.value = true;
  await getAccountMembers();
};

const getAccountMembers = async () => {
  if (!currentAccountId.value) return;
  try {
    loading.value = true;
    const res = await getPageMemberByAccount({
      account_id: currentAccountId.value,
      page: accountMemberQuery.value.page,
      size: accountMemberQuery.value.size
    });
    if (res.data) {
      accountMembers.value = res.data.records;
      accountMemberTotal.value = res.data.pagination.total;
    }
  } finally {
    loading.value = false;
  }
};

const handleViewMemberAccounts = async (memberId: number) => {
  if (!currentTeam.value) return;
  currentMemberId.value = memberId;
  memberAccountQuery.value.team_id = currentTeam.value.id;
  memberAccountQuery.value.member_id = memberId;
  memberAccountDialogVisible.value = true;
  await getMemberAccounts();
};

const getMemberAccounts = async () => {
  if (!currentMemberId.value || !currentTeam.value) return;
  try {
    loading.value = true;
    const res = await getPageAccountByMember({
      team_id: currentTeam.value.id,
      member_id: currentMemberId.value,
      page: memberAccountQuery.value.page,
      size: memberAccountQuery.value.size
    });
    if (res.data) {
      memberAccounts.value = res.data.records;
      memberAccountTotal.value = res.data.pagination.total;
    }
  } finally {
    loading.value = false;
  }
};

const submitCreateAccount = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate(async valid => {
    if (valid) {
      try {
        loading.value = true;
        await createTeamAccount(createAccountForm.value);
        ElMessage.success("公共账号创建申请已提交，请等待审核");
        createAccountDialogVisible.value = false;
        // 重置表单
        createAccountForm.value = {
          team_id: currentTeam.value?.id || 1,
          account_name: "",
          description: ""
        };
        // 刷新账号列表
        getAccounts();
      } catch (error: any) {
        ElMessage.error(error.message || "创建账号失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

const cancelCreateAccount = () => {
  createAccountDialogVisible.value = false;
  createAccountForm.value = {
    team_id: currentTeam.value?.id || 1,
    account_name: "",
    description: ""
  };
};

const handleViewAccountHistory = async () => {
  if (!currentTeam.value) {
    ElMessage.warning("请先选择团队");
    return;
  }
  accountHistoryQuery.value.team_id = currentTeam.value.id;
  accountHistoryDialogVisible.value = true;
  await getAccountHistory();
};

const getAccountHistory = async () => {
  if (!currentTeam.value) return;
  try {
    loading.value = true;
    const res = await getMyTeamAccount({
      team_id: currentTeam.value.id,
      page: accountHistoryQuery.value.page,
      size: accountHistoryQuery.value.size
    });
    if (res.data) {
      accountHistoryList.value = res.data.records;
      accountHistoryTotal.value = res.data.pagination.total;
    }
  } finally {
    loading.value = false;
  }
};

const submitAddMember = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate(async valid => {
    if (valid) {
      try {
        loading.value = true;
        await addTeamMember(addMemberForm.value);
        ElMessage.success("添加成员成功");
        addMemberDialogVisible.value = false;
        // 重置表单
        addMemberForm.value = {
          team_id: currentTeam.value?.id || 1,
          henau_number: "",
          name: "",
          role: "member"
        };
        // 刷新成员列表
        getMembers();
      } catch (error: any) {
        ElMessage.error(error.message || "添加成员失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

const cancelAddMember = () => {
  addMemberDialogVisible.value = false;
  addMemberForm.value = {
    team_id: currentTeam.value?.id || 1,
    henau_number: "",
    name: "",
    role: "member"
  };
};

const handleViewApplyJoin = async () => {
  if (!currentTeam.value) {
    ElMessage.warning("请先选择团队");
    return;
  }
  applyJoinQuery.value.team_id = currentTeam.value.id;
  applyJoinDialogVisible.value = true;
  await getApplyJoin();
};

const getApplyJoin = async () => {
  if (!currentTeam.value) return;
  try {
    loading.value = true;
    const res = await getpageApplyJoin({
      team_id: currentTeam.value.id,
      page: applyJoinQuery.value.page,
      size: applyJoinQuery.value.size
    });
    if (res.data) {
      applyJoinList.value = res.data.records;
      applyJoinTotal.value = res.data.pagination.total;
    }
  } finally {
    loading.value = false;
  }
};

const handleApproveJoin = async (row: ApplyJoinInfo) => {
  try {
    loading.value = true;
    await approvalJoinTeam({
      application_id: row.id,
      status: "approved"
    });
    ElMessage.success("审批通过成功");
    getApplyJoin();
  } catch (error: any) {
    ElMessage.error(error.message || "审批失败");
  } finally {
    loading.value = false;
  }
};

const handleRejectJoin = async (row: ApplyJoinInfo) => {
  try {
    loading.value = true;
    await approvalJoinTeam({
      application_id: row.id,
      status: "rejected"
    });
    ElMessage.success("已拒绝申请");
    getApplyJoin();
  } catch (error: any) {
    ElMessage.error(error.message || "操作失败");
  } finally {
    loading.value = false;
  }
};

// 添加新的方法
const handleAddMemberToAccount = () => {
  accountMemberActiveTab.value = "qrcode"; // 切换到二维码标签页
  addMemberToAccountDialogVisible.value = true;
  searchTeamMembers();
};

const searchTeamMembers = async () => {
  if (!currentTeam.value) return;
  try {
    teamMemberSearchLoading.value = true;
    const res = await getTeamMembersByPage({
      team_id: currentTeam.value.id,
      page: 1,
      size: 50
    });
    if (res.data) {
      teamMemberSearchList.value = res.data.records;
    }
  } catch (error: any) {
    ElMessage.error(error.message || "获取团队成员失败");
  } finally {
    teamMemberSearchLoading.value = false;
  }
};

const handleConfirmAddMemberToAccount = async () => {
  if (
    !selectedTeamMemberId.value ||
    !currentAccountId.value ||
    !currentTeam.value
  ) {
    ElMessage.warning("请选择要添加的成员");
    return;
  }

  try {
    await addAccountMember({
      team_id: currentTeam.value.id,
      account_id: currentAccountId.value,
      member_id: selectedTeamMemberId.value
    });
    ElMessage.success("添加成功");
    addMemberToAccountDialogVisible.value = false;
    selectedTeamMemberId.value = null;
    getAccountMembers();
  } catch (error: any) {
    ElMessage.error(error.message || "添加失败");
  }
};

const cancelAddMemberToAccount = () => {
  addMemberToAccountDialogVisible.value = false;
  selectedTeamMemberId.value = null;
};

const filteredTeamMembers = computed(() => {
  if (!teamMemberSearchQuery.value) {
    return teamMemberSearchList.value;
  }
  const query = teamMemberSearchQuery.value.toLowerCase();
  return teamMemberSearchList.value.filter(
    member =>
      member.name.toLowerCase().includes(query) ||
      member.henau_number.toLowerCase().includes(query)
  );
});

const handleEditRole = (row: MemberInfo) => {
  currentEditMember.value = row;
  editRoleForm.value.role = row.role;
  editRoleDialogVisible.value = true;
};

const submitEditRole = async () => {
  if (!currentEditMember.value || !currentTeam.value) return;

  try {
    loading.value = true;
    await updateMemberRole({
      team_id: currentTeam.value.id,
      member_id: currentEditMember.value.id,
      role: editRoleForm.value.role,
      status: editRoleForm.value.status
    });
    ElMessage.success("修改角色成功");
    editRoleDialogVisible.value = false;
    getMembers();
  } catch (error: any) {
    ElMessage.error(error.message || "修改角色失败");
  } finally {
    loading.value = false;
  }
};

const cancelEditRole = () => {
  editRoleDialogVisible.value = false;
  currentEditMember.value = null;
  editRoleForm.value = {
    role: "",
    status: "approved"
  };
};

const handleStopMember = async (row: AccountMemberInfo) => {
  try {
    loading.value = true;
    await stopAccountMember({
      account_id: row.account_id,
      member_id: row.member_id
    });
    ElMessage.success("停用成功");
    getAccountMembers();
  } catch (error: any) {
    ElMessage.error(error.message || "停用失败");
  } finally {
    loading.value = false;
  }
};

const handleStartMember = async (row: AccountMemberInfo) => {
  try {
    loading.value = true;
    await startAccountMember({
      account_id: row.account_id,
      member_id: row.member_id
    });
    ElMessage.success("启用成功");
    getAccountMembers();
  } catch (error: any) {
    ElMessage.error(error.message || "启用失败");
  } finally {
    loading.value = false;
  }
};

const saveQRCode = async () => {
  if (!qrcodeRef.value || !currentTeam.value) return;

  try {
    loading.value = true;
    const svg = qrcodeRef.value.querySelector("svg");
    if (!svg) return;

    // 创建一个新的 canvas
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    // 设置画布大小
    canvas.width = 400;
    canvas.height = 500;

    // 填充白色背景
    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 将SVG转换为图片
    const svgData = new XMLSerializer().serializeToString(svg);
    const img = new Image();

    await new Promise((resolve, reject) => {
      img.onload = () => {
        try {
          // 在中间位置绘制二维码
          ctx.drawImage(img, 100, 100, 200, 200);

          // 添加文字
          ctx.fillStyle = "#333333";
          ctx.textAlign = "center";

          // 绘制团队名称
          ctx.font = "bold 24px Arial";
          ctx.fillText(currentTeam.value!.name, canvas.width / 2, 50);

          // 绘制UUID
          ctx.font = "16px Arial";
          ctx.fillText(
            `UUID: ${currentTeam.value!.uuid}`,
            canvas.width / 2,
            350
          );

          // 绘制提示文字
          ctx.font = "14px Arial";
          ctx.fillText("扫描上方二维码加入团队", canvas.width / 2, 400);

          resolve(null);
        } catch (err) {
          reject(err);
        }
      };
      img.onerror = () => reject(new Error("图片加载失败"));

      img.src = "data:image/svg+xml;base64," + btoa(svgData);
    });

    // 转换为图片并下载
    const link = document.createElement("a");
    link.download = `${currentTeam.value.name}_team_qrcode.png`;
    link.href = canvas.toDataURL("image/png");
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success("二维码已保存");
  } catch (error) {
    console.error("保存二维码时出错:", error);
    ElMessage.error("保存二维码失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 添加新的方法
const handleAddAccountToMember = async () => {
  if (!currentTeam.value || !currentMemberId.value) return;
  availableAccountsQuery.value.team_id = currentTeam.value.id;
  addAccountToMemberDialogVisible.value = true;
  await getAvailableAccounts();
};

const getAvailableAccounts = async () => {
  if (!currentTeam.value) return;
  try {
    loading.value = true;
    const res = await getTeamAccountsByPage({
      team_id: currentTeam.value.id,
      page: availableAccountsQuery.value.page,
      size: availableAccountsQuery.value.size
    });
    if (res.data) {
      availableAccounts.value = res.data.records;
      availableAccountsTotal.value = res.data.pagination.total;
    }
  } finally {
    loading.value = false;
  }
};

const handleConfirmAddAccountToMember = async () => {
  if (
    !selectedAccountId.value ||
    !currentMemberId.value ||
    !currentTeam.value
  ) {
    ElMessage.warning("请选择要添加的账号");
    return;
  }

  try {
    loading.value = true;
    await addAccountMember({
      team_id: currentTeam.value.id,
      account_id: selectedAccountId.value,
      member_id: currentMemberId.value
    });
    ElMessage.success("添加成功");
    addAccountToMemberDialogVisible.value = false;
    selectedAccountId.value = null;
    getMemberAccounts();
  } catch (error: any) {
    ElMessage.error(error.message || "添加失败");
  } finally {
    loading.value = false;
  }
};

const cancelAddAccountToMember = () => {
  addAccountToMemberDialogVisible.value = false;
  selectedAccountId.value = null;
};

const getAccountOAuthUrl = computed(() => {
  if (!currentTeam.value || !currentAccountId.value) return "";
  // 获取当前账号信息
  const currentAccount = accountList.value.find(
    account => account.id === currentAccountId.value
  );
  if (!currentAccount) return "";

  const redirectUri = encodeURIComponent(
    `${window.location.origin}/#/ApproveAccount?uuid=${currentTeam.value.uuid}&account_number=${currentAccount.account_number}&account_id=${currentAccountId.value}&team_name=${encodeURIComponent(currentTeam.value.name)}&account_name=${encodeURIComponent(currentAccount.name)}&code=CODE_PLACEHOLDER`
  );
  return `https://oauth.henau.edu.cn/oauth2_connect/authorize?appid=ndd956a392c8b55d39&redirect_uri=${redirectUri}&response_type=code&scope=henauapi_userinfo`;
});

const saveAccountQRCode = async () => {
  if (!accountQrcodeRef.value || !currentTeam.value || !currentAccountId.value)
    return;

  const currentAccount = accountList.value.find(
    account => account.id === currentAccountId.value
  );
  if (!currentAccount) return;

  try {
    loading.value = true;
    const svg = accountQrcodeRef.value.querySelector("svg");
    if (!svg) return;

    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    canvas.width = 400;
    canvas.height = 500;

    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    const svgData = new XMLSerializer().serializeToString(svg);
    const img = new Image();

    await new Promise((resolve, reject) => {
      img.onload = () => {
        try {
          ctx.drawImage(img, 100, 100, 200, 200);

          ctx.fillStyle = "#333333";
          ctx.textAlign = "center";

          ctx.font = "bold 24px Arial";
          ctx.fillText(currentTeam.value!.name, canvas.width / 2, 50);

          ctx.font = "16px Arial";
          ctx.fillText(
            `账号名称: ${currentAccount.name}`,
            canvas.width / 2,
            350
          );
          ctx.fillText(
            `账号: ${currentAccount.account_number}`,
            canvas.width / 2,
            380
          );

          ctx.font = "14px Arial";
          ctx.fillText("扫描上方二维码加入账号", canvas.width / 2, 420);

          resolve(null);
        } catch (err) {
          reject(err);
        }
      };
      img.onerror = () => reject(new Error("图片加载失败"));

      img.src = "data:image/svg+xml;base64," + btoa(svgData);
    });

    const link = document.createElement("a");
    link.download = `${currentTeam.value.name}_account_qrcode.png`;
    link.href = canvas.toDataURL("image/png");
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success("二维码已保存");
  } catch (error) {
    console.error("保存二维码时出错:", error);
    ElMessage.error("保存二维码失败，请重试");
  } finally {
    loading.value = false;
  }
};

const handleViewApplyJoinAccount = async () => {
  if (!currentTeam.value || !currentAccountId.value) {
    ElMessage.warning("请先选择团队和账号");
    return;
  }
  applyJoinAccountQuery.value.team_id = currentTeam.value.id;
  applyJoinAccountQuery.value.account_id = currentAccountId.value;
  applyJoinAccountDialogVisible.value = true;
  await getApplyJoinAccount();
};

const getApplyJoinAccount = async () => {
  if (!currentTeam.value || !currentAccountId.value) return;
  try {
    loading.value = true;
    const res = await getPageApplyJoinTeamAccount({
      team_id: currentTeam.value.id,
      account_id: currentAccountId.value,
      page: applyJoinAccountQuery.value.page,
      size: applyJoinAccountQuery.value.size
    });
    if (res.data) {
      applyJoinAccountList.value = res.data.records;
      applyJoinAccountTotal.value = res.data.pagination.total;
    }
  } finally {
    loading.value = false;
  }
};

const handleApproveJoinAccount = async (row: ApplyJoinAccountInfo) => {
  try {
    loading.value = true;
    await approvalJoinTeamAccount({
      application_id: row.id,
      status: "approved"
    });
    ElMessage.success("审批通过成功");
    getApplyJoinAccount();
  } catch (error: any) {
    ElMessage.error(error.message || "审批失败");
  } finally {
    loading.value = false;
  }
};

const handleRejectJoinAccount = async (row: ApplyJoinAccountInfo) => {
  try {
    loading.value = true;
    await approvalJoinTeamAccount({
      application_id: row.id,
      status: "rejected"
    });
    ElMessage.success("已拒绝申请");
    getApplyJoinAccount();
  } catch (error: any) {
    ElMessage.error(error.message || "操作失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getTeams();
});
</script>

<template>
  <div>
    <div class="team-container">
      <el-row :gutter="20">
        <!-- 左侧团队信息卡片 -->
        <el-col :span="6">
          <el-card class="team-info-card">
            <template #header>
              <div class="card-header">
                <span>团队信息</span>
                <div class="header-right">
                  <el-button
                    type="primary"
                    size="small"
                    :icon="Plus"
                    @click="handleApplyTeam"
                  >
                    申请团队
                  </el-button>
                  <el-select
                    v-model="currentTeam"
                    placeholder="选择团队"
                    :loading="loading"
                    value-key="id"
                    @change="handleTeamChange"
                  >
                    <el-option
                      v-for="team in teamList"
                      :key="team.id"
                      :label="team.name"
                      :value="team"
                    />
                  </el-select>
                </div>
              </div>
            </template>
            <div v-if="currentTeam" class="team-info">
              <h3>{{ currentTeam.name }}</h3>
              <p class="description">
                {{ currentTeam.description || "暂无描述" }}
              </p>
              <div class="info-item">
                <span class="label">状态：</span>
                <el-tag
                  :type="
                    currentTeam.status === 'approved' ? 'success' : 'warning'
                  "
                >
                  {{ currentTeam.status === "approved" ? "已批准" : "待审批" }}
                </el-tag>
              </div>
              <div class="info-item">
                <span class="label">团队ID：</span>
                <span>{{ currentTeam.uuid }}</span>
              </div>
              <div class="info-item">
                <span class="label">创建时间：</span>
                <span>{{ currentTeam.created_at }}</span>
              </div>
              <div class="info-item">
                <span class="label">更新时间：</span>
                <span>{{ currentTeam.updated_at }}</span>
              </div>
            </div>
            <el-empty v-else description="暂无团队信息" />
          </el-card>
        </el-col>

        <!-- 右侧内容区 -->
        <el-col :span="18">
          <!-- 上部分：人员分布 -->
          <!--<el-card class="content-card">
            <template #header>
              <div class="card-header">
                <span>人员分布</span>
                <div class="header-right">
                  <el-button
                    type="primary"
                    size="small"
                    :icon="Plus"
                    @click="handleAddMember"
                  >
                    添加人员
                  </el-button>
                  <el-button
                    type="info"
                    size="small"
                    :icon="Edit"
                    @click="handleViewApplyJoin"
                  >
                    审批申请
                  </el-button>
                </div>
              </div>
            </template>
            <el-table
              v-loading="loading"
              :data="memberList"
              style="width: 100%"
            >
              <el-table-column prop="henau_number" label="学工号" />
              <el-table-column prop="name" label="姓名" />
              <el-table-column prop="role" label="角色">
                <template #default="{ row }">
                  <el-tag :type="getRoleTagType(row.role)">
                    {{ getRoleText(row.role) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                  <el-tag
                    :type="row.status === 'approved' ? 'success' : 'warning'"
                  >
                    {{ row.status === "approved" ? "启用" : "停用" }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="created_at" label="加入时间" />
              <el-table-column label="操作" width="220">
                <template #default="{ row }">
                  <div class="operation-buttons">
                    <el-button
                      type="success"
                      size="small"
                      :icon="Edit"
                      @click="handleRemoveMember(row)"
                    >
                      使用账号
                    </el-button>
                    <el-tag
                      type="warning"
                      class="edit-tag"
                      @click="handleEditRole(row)"
                    >
                      <el-icon class="edit-icon"><Edit /></el-icon>
                      修改信息
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination">
              <el-pagination
                v-model:current-page="memberQuery.page"
                v-model:page-size="memberQuery.size"
                :total="memberTotal"
                @current-change="getMembers"
                @size-change="getMembers"
              />
            </div>
          </el-card>-->

          <!-- 下部分：账号列表 -->
          <el-card class="content-card">
            <template #header>
              <div class="card-header">
                <span>公共账号列表</span>
                <div class="header-right">
                  <el-button
                    type="primary"
                    size="small"
                    :icon="Plus"
                    @click="handleAddAccount"
                  >
                    申请账号
                  </el-button>
                  <el-button
                    type="info"
                    size="small"
                    :icon="Edit"
                    @click="handleViewAccountHistory"
                  >
                    申请历史
                  </el-button>
                </div>
              </div>
            </template>
            <el-table
              v-loading="loading"
              :data="accountList"
              style="width: 100%"
            >
              <el-table-column prop="account_number" label="账号" />
              <el-table-column prop="name" label="名称" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                  <el-tag
                    :type="row.status === 'approved' ? 'success' : 'warning'"
                  >
                    {{ row.status === "approved" ? "启用" : "停用" }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="created_at" label="创建时间" />
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <el-button
                    type="success"
                    size="small"
                    :icon="User"
                    style="cursor: pointer"
                    @click="handleViewAccountMembers(row.id)"
                  >
                    使用人员
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination">
              <el-pagination
                v-model:current-page="accountQuery.page"
                v-model:page-size="accountQuery.size"
                :total="accountTotal"
                @current-change="getAccounts"
                @size-change="getAccounts"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 创建团队对话框 -->
    <el-dialog
      v-model="createTeamDialogVisible"
      title="申请团队"
      width="500px"
      @close="cancelCreateTeam"
    >
      <el-form
        ref="createTeamFormRef"
        :model="createTeamForm"
        :rules="createTeamRules"
        label-width="80px"
      >
        <el-form-item label="团队名称" prop="team_name">
          <el-input
            v-model="createTeamForm.team_name"
            placeholder="请输入团队名称"
          />
        </el-form-item>
        <el-form-item label="团队描述" prop="description">
          <el-input
            v-model="createTeamForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入团队描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelCreateTeam">取消</el-button>
          <el-button
            type="primary"
            @click="submitCreateTeam(createTeamFormRef)"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 账号成员对话框 -->
    <el-dialog
      v-model="accountMemberDialogVisible"
      title="账号使用人员"
      width="800px"
    >
      <div class="dialog-header" style="margin-bottom: 20px">
        <el-button
          type="primary"
          size="small"
          @click="handleAddMemberToAccount"
        >
          添加使用人员
        </el-button>
        <el-button type="info" size="small" @click="handleViewApplyJoinAccount">
          待审批人员
        </el-button>
      </div>
      <el-table v-loading="loading" :data="accountMembers" style="width: 100%">
        <el-table-column prop="henau_number" label="学工号" />
        <el-table-column prop="member_name" label="姓名" />
        <el-table-column prop="team_role" label="角色">
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.team_role)">
              {{ getRoleText(row.team_role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'approved' ? 'success' : 'warning'">
              {{ row.status === "approved" ? "启用" : "停用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="添加时间" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'approved'"
              type="danger"
              size="small"
              @click="handleStopMember(row)"
            >
              停用
            </el-button>
            <el-button
              v-else
              type="success"
              size="small"
              @click="handleStartMember(row)"
            >
              启用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="accountMemberQuery.page"
          v-model:page-size="accountMemberQuery.size"
          :total="accountMemberTotal"
          @current-change="getAccountMembers"
          @size-change="getAccountMembers"
        />
      </div>
    </el-dialog>

    <!-- 添加使用人员对话框 -->
    <el-dialog
      v-model="addMemberToAccountDialogVisible"
      title="添加使用人员"
      width="500px"
      class="qrcode-dialog"
    >
      <div class="qrcode-container">
        <div v-if="currentTeam && currentAccountId" class="qrcode-content">
          <div class="team-info-display">
            <h3>{{ currentTeam.name }}</h3>
            <div class="info-divider" />
            <div class="account-info-row">
              <span class="info-label">账号名称:</span>
              <span class="info-value">{{
                accountList.find(account => account.id === currentAccountId)
                  ?.name
              }}</span>
            </div>
            <div class="account-info-row">
              <span class="info-label">账号:</span>
              <span class="info-value">{{
                accountList.find(account => account.id === currentAccountId)
                  ?.account_number
              }}</span>
            </div>
          </div>
          <div ref="accountQrcodeRef" class="qrcode-wrapper">
            <QRCode
              :value="getAccountOAuthUrl"
              :size="200"
              level="H"
              render-as="svg"
              class="qrcode"
            />
          </div>
          <div class="action-area">
            <el-button
              type="primary"
              class="save-button"
              @click="saveAccountQRCode"
            >
              <el-icon><Download /></el-icon>
              保存二维码
            </el-button>
            <p class="qrcode-tip">请使用手机扫描二维码加入账号</p>
          </div>
        </div>
        <el-empty v-else description="请先选择团队和账号" />
      </div>
    </el-dialog>

    <!-- 成员账号对话框 -->
    <el-dialog
      v-model="memberAccountDialogVisible"
      title="可使用的账号"
      width="800px"
    >
      <div class="dialog-header" style="margin-bottom: 20px">
        <el-button
          type="primary"
          size="small"
          @click="handleAddAccountToMember"
        >
          添加使用账号
        </el-button>
      </div>
      <el-table v-loading="loading" :data="memberAccounts" style="width: 100%">
        <el-table-column prop="account_number" label="账号" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'approved' ? 'success' : 'warning'">
              {{ row.status === "approved" ? "启用" : "停用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" />
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="memberAccountQuery.page"
          v-model:page-size="memberAccountQuery.size"
          :total="memberAccountTotal"
          @current-change="getMemberAccounts"
          @size-change="getMemberAccounts"
        />
      </div>
    </el-dialog>

    <!-- 创建账号对话框 -->
    <el-dialog
      v-model="createAccountDialogVisible"
      title="申请公共账号"
      width="500px"
      @close="cancelCreateAccount"
    >
      <el-form
        ref="createAccountFormRef"
        :model="createAccountForm"
        :rules="createAccountRules"
        label-width="80px"
      >
        <el-form-item label="账号名称" prop="account_name">
          <el-input
            v-model="createAccountForm.account_name"
            placeholder="请输入账号名称"
          />
        </el-form-item>
        <el-form-item label="账号描述" prop="description">
          <el-input
            v-model="createAccountForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入账号描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelCreateAccount">取消</el-button>
          <el-button
            type="primary"
            @click="submitCreateAccount(createAccountFormRef)"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 申请历史对话框 -->
    <el-dialog
      v-model="accountHistoryDialogVisible"
      title="账号申请历史"
      width="900px"
    >
      <el-table
        v-loading="loading"
        :data="accountHistoryList"
        style="width: 100%"
      >
        <el-table-column prop="account_name" label="账号名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="team_name" label="团队" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'approved' ? 'success' : 'warning'">
              {{ row.status === "approved" ? "启用" : "停用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reviewer_name" label="审核人">
          <template #default="{ row }">
            {{ row.reviewer_name || "待审核" }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="申请时间" />
        <el-table-column prop="updated_at" label="更新时间" />
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="accountHistoryQuery.page"
          v-model:page-size="accountHistoryQuery.size"
          :total="accountHistoryTotal"
          @current-change="getAccountHistory"
          @size-change="getAccountHistory"
        />
      </div>
    </el-dialog>

    <!-- 添加成员对话框 -->
    <el-dialog
      v-model="addMemberDialogVisible"
      title="添加团队成员"
      width="500px"
      @close="cancelAddMember"
    >
      <el-tabs v-model="activeTab">
        <el-tab-pane label="扫码加入" name="qrcode">
          <div class="qrcode-container">
            <div v-if="currentTeam" class="qrcode-content">
              <div class="team-info-display">
                <h3>{{ currentTeam.name }}</h3>
                <p>团队 UUID: {{ currentTeam.uuid }}</p>
              </div>
              <div ref="qrcodeRef" class="qrcode-wrapper">
                <QRCode
                  :value="getOAuthUrl"
                  :size="200"
                  level="H"
                  render-as="svg"
                />
                <div class="qrcode-text">
                  <div class="team-name">{{ currentTeam.name }}</div>
                  <div class="team-uuid">UUID: {{ currentTeam.uuid }}</div>
                </div>
              </div>
              <el-button type="primary" @click="saveQRCode">
                <el-icon><Download /></el-icon>
                保存二维码
              </el-button>
              <p class="qrcode-tip">请使用手机扫描二维码加入团队</p>
            </div>
            <el-empty v-else description="请先选择团队" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="手动添加" name="manual">
          <el-form
            ref="addMemberFormRef"
            :model="addMemberForm"
            :rules="addMemberRules"
            label-width="80px"
          >
            <el-form-item label="学工号" prop="henau_number">
              <el-input
                v-model="addMemberForm.henau_number"
                placeholder="请输入学工号"
              />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="addMemberForm.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="角色" prop="role">
              <el-select v-model="addMemberForm.role" placeholder="请选择角色">
                <el-option label="管理员" value="admin" />
                <el-option label="组员" value="member" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAddMember">取消</el-button>
          <el-button
            type="primary"
            :disabled="activeTab === 'qrcode'"
            @click="submitAddMember(addMemberFormRef)"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 加入申请审批对话框 -->
    <el-dialog
      v-model="applyJoinDialogVisible"
      title="加入申请审批"
      width="900px"
    >
      <el-table v-loading="loading" :data="applyJoinList" style="width: 100%">
        <el-table-column prop="initiator_henau_number" label="申请人学工号" />
        <el-table-column prop="initiator_name" label="申请人姓名" />
        <el-table-column prop="team_name" label="团队名称" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag
              :type="
                row.status === 'approved'
                  ? 'success'
                  : row.status === 'rejected'
                    ? 'danger'
                    : 'warning'
              "
            >
              {{
                row.status === "approved"
                  ? "已批准"
                  : row.status === "rejected"
                    ? "已拒绝"
                    : "待审批"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reviewer_name" label="审核人">
          <template #default="{ row }">
            {{ row.reviewer_name || "待审核" }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="申请时间" />
        <el-table-column prop="updated_at" label="更新时间" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-tag
              v-if="row.status === 'pending'"
              type="success"
              style="margin-right: 10px; cursor: pointer"
              @click="handleApproveJoin(row)"
            >
              通过
            </el-tag>
            <el-tag
              v-if="row.status === 'pending'"
              type="danger"
              style="cursor: pointer"
              @click="handleRejectJoin(row)"
            >
              拒绝
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="applyJoinQuery.page"
          v-model:page-size="applyJoinQuery.size"
          :total="applyJoinTotal"
          @current-change="getApplyJoin"
          @size-change="getApplyJoin"
        />
      </div>
    </el-dialog>

    <!-- 加入申请审批对话框 -->
    <el-dialog
      v-model="applyJoinAccountDialogVisible"
      title="加入申请审批"
      width="900px"
    >
      <el-table
        v-loading="loading"
        :data="applyJoinAccountList"
        style="width: 100%"
      >
        <el-table-column prop="initiator_henau_number" label="申请人学工号" />
        <el-table-column prop="initiator_name" label="申请人姓名" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag
              :type="
                row.status === 'approved'
                  ? 'success'
                  : row.status === 'rejected'
                    ? 'danger'
                    : 'warning'
              "
            >
              {{
                row.status === "approved"
                  ? "已批准"
                  : row.status === "rejected"
                    ? "已拒绝"
                    : "待审批"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="申请时间" />
        <el-table-column prop="updated_at" label="更新时间" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-tag
              v-if="row.status === 'pending'"
              type="success"
              style="margin-right: 10px; cursor: pointer"
              @click="handleApproveJoinAccount(row)"
            >
              通过
            </el-tag>
            <el-tag
              v-if="row.status === 'pending'"
              type="danger"
              style="cursor: pointer"
              @click="handleRejectJoinAccount(row)"
            >
              拒绝
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="applyJoinAccountQuery.page"
          v-model:page-size="applyJoinAccountQuery.size"
          :total="applyJoinAccountTotal"
          @current-change="getApplyJoinAccount"
          @size-change="getApplyJoinAccount"
        />
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.team-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 160px);
  padding: 20px;

  .el-row {
    flex: 1;
    min-height: 0;
  }

  .el-col {
    height: 100%;
  }

  .team-info-card {
    height: calc(100% - 20px);
    margin-bottom: 20px;
    overflow-y: auto;

    .team-info {
      padding: 10px;
    }
  }

  .content-card {
    display: flex;
    flex-direction: column;
    height: calc(100% - 20px);
    margin-bottom: 20px;

    :deep(.el-card__body) {
      flex: 1;
      padding: 10px;
      overflow-y: auto;
    }
  }

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 0;

    .header-right {
      display: flex;
      gap: 10px;
      align-items: center;
    }
  }

  .team-info {
    .description {
      margin: 15px 0;
      color: #666;
      word-break: break-all;
      white-space: pre-wrap;
    }

    .info-item {
      margin: 10px 0;

      .label {
        margin-right: 8px;
        color: #888;
      }
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }

  :deep(.el-button) {
    display: flex;
    gap: 4px;
    align-items: center;
  }

  .qrcode-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;

    .qrcode-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 100%;
      max-width: 400px;
    }

    .team-info-display {
      margin-bottom: 20px;
      text-align: center;

      h3 {
        margin: 0 0 10px;
        font-size: 24px;
        color: #333;
      }

      p {
        margin: 0;
        font-size: 14px;
        color: #666;
      }
    }

    .qrcode-wrapper {
      padding: 20px;
      margin-bottom: 20px;
      text-align: center;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgb(0 0 0 / 10%);

      img {
        width: 200px;
        height: 200px;
        margin-bottom: 15px;
      }

      .qrcode-text {
        .team-name {
          margin-bottom: 5px;
          font-size: 16px;
          font-weight: bold;
          color: #333;
        }

        .team-uuid {
          font-size: 14px;
          color: #666;
        }
      }
    }

    .qrcode-tip {
      margin-top: 15px;
      font-size: 14px;
      color: #666;
    }
  }

  .search-container {
    padding: 20px;

    .el-input {
      width: 100%;
      margin-bottom: 20px;
    }

    .member-list {
      width: 100%;
      max-height: 300px;
      padding: 10px;
      overflow-y: auto;
      border: 1px solid #ebeef5;
      border-radius: 4px;

      .member-item {
        padding: 8px;
        margin-bottom: 10px;
        border-radius: 4px;
        transition: background-color 0.3s;

        &:hover {
          background-color: #f5f7fa;
        }

        &:last-child {
          margin-bottom: 0;
        }

        .el-radio {
          width: 100%;
          height: 100%;
          padding: 4px 8px;
          margin-right: 0;
        }
      }
    }
  }

  .operation-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
  }

  .edit-tag {
    display: flex;
    gap: 4px;
    align-items: center;
    height: 24px;
    padding: 4px 8px;
    line-height: 16px;
    cursor: pointer;

    .edit-icon {
      font-size: 14px;
    }
  }

  .account-list {
    max-height: 400px;
    padding: 10px;
    overflow-y: auto;
    border: 1px solid #ebeef5;
    border-radius: 4px;

    .account-radio-group {
      width: 100%;

      .account-item {
        padding: 12px;
        margin-bottom: 10px;
        border-radius: 4px;
        transition: background-color 0.3s;

        &:hover {
          background-color: #f5f7fa;
        }

        &:last-child {
          margin-bottom: 0;
        }

        .el-radio {
          width: 100%;
          height: 100%;
          margin-right: 0;

          :deep(.el-radio__label) {
            width: 100%;
          }
        }

        .account-info {
          .account-name {
            display: flex;
            gap: 8px;
            align-items: center;
            margin-bottom: 4px;
            font-weight: bold;
          }

          .account-description {
            font-size: 13px;
            color: #666;
          }
        }
      }
    }
  }
}

// 添加页脚样式
.page-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
  margin-top: 20px;
  font-size: 14px;
  color: #909399;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.qrcode-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.qrcode-container {
  .qrcode-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 24px;

    .team-info-display {
      width: 100%;
      padding: 16px;
      margin-bottom: 24px;
      text-align: center;
      background: #f8f9fa;
      border-radius: 8px;

      h3 {
        margin: 0 0 16px;
        font-size: 24px;
        font-weight: 600;
        color: #303133;
      }

      .info-divider {
        width: 40px;
        height: 2px;
        margin: 16px auto;
        background: #409eff;
      }

      .account-info-row {
        display: flex;
        gap: 8px;
        align-items: center;
        justify-content: center;
        margin-bottom: 8px;

        &:last-child {
          margin-bottom: 0;
        }

        .info-label {
          font-size: 14px;
          color: #909399;
        }

        .info-value {
          font-size: 16px;
          font-weight: 500;
          color: #303133;
        }
      }
    }

    .qrcode-wrapper {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 240px;
      height: 240px;
      padding: 20px;
      margin-bottom: 24px;
      background: #fff;
      border: 1px solid #ebeef5;
      border-radius: 12px;
      box-shadow: 0 2px 12px rgb(0 0 0 / 8%);

      .qrcode {
        width: 200px;
        height: 200px;
      }
    }

    .action-area {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 100%;

      .save-button {
        display: flex;
        gap: 8px;
        align-items: center;
        padding: 12px 24px;
        margin-bottom: 16px;
        font-size: 16px;

        .el-icon {
          font-size: 18px;
        }
      }

      .qrcode-tip {
        margin: 0;
        font-size: 14px;
        color: #909399;
      }
    }
  }
}
</style>
